package cn.sylinx.horm.starter;

import java.util.HashMap;
import java.util.Map;

import cn.sylinx.horm.config.SingleDataSourceConfig;
import cn.sylinx.horm.core.datasource.NamedDataSource;
import cn.sylinx.horm.dialect.DbType;
import cn.sylinx.horm.exception.HORMException;
import cn.sylinx.horm.pool.DataSourceWrapperFactory;
import cn.sylinx.horm.util.GLog;
import cn.sylinx.horm.util.StrKit;

public final class Utils {

    public static NamedDataSource build(SingleDataSourceConfig singleDataSourceConfig) {

        String url = singleDataSourceConfig.getUrl();
        String driver = singleDataSourceConfig.getDriver();
        String dbtype = singleDataSourceConfig.getDbtype();
        if (StrKit.isBlank(url) || StrKit.isBlank(driver) || StrKit.isBlank(dbtype)) {
            throw new HORMException("数据源参数配置丢失");
        }

        DbType dbTypeEnum = DbType.getDbType(dbtype);
        GLog.debug("Use DbType:{}", dbTypeEnum.getValue());

        String pooltype = singleDataSourceConfig.getPooltype();
        String username = singleDataSourceConfig.getUsername();
        String password = singleDataSourceConfig.getPassword();
        String name = singleDataSourceConfig.getName();

        Map<String, Object> dsMap = new HashMap<>();
        dsMap.put("dbtype", dbtype);
        dsMap.put("pooltype", pooltype);
        dsMap.put("name", name);
        dsMap.put("url", url);
        dsMap.put("driver", driver);
        dsMap.put("username", username);
        dsMap.put("password", password);

        // 默认数据源额外配置
        Map<String, Object> extConfig = singleDataSourceConfig.getPoolConfig();
        // 获取单（默认）数据源
        return DataSourceWrapperFactory.buildDataSource(dsMap, extConfig);
    }
}
